// 导出一个axios的实例  而且这个实例要有请求拦截器 响应拦截器
// import axios from 'axios'
// const service = axios.create() // 创建一个axios的实例
// service.interceptors.request.use() // 请求拦截器
// service.interceptors.response.use() // 响应拦截器
// export default service // 导出axios实例
import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
// 由于页面的跳转需要路由才引入
import router from '@/router'
// import { getToken } from '@/utils/auth'/
// import { setToken } from '@/'
// create an axios instance
const service = axios.create({
//   baseURL: 'http://localhost:3000/api/sys/login',
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // const token = store.state.user.token
    const token = store.getters.token
    console.log(token)
    // 如果当前存有token就加在请求头上
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(

  response => {
    const data = response.data
    if (data.success) {
      return data
    } else {
      return Promise.reject(new Error(data.message))
    }
    // const res = response.data

    // // if the custom code is not 20000, it is judged as an error.
    // if (res.code !== 20000) {
    //   Message({
    //     message: res.message || 'Error',
    //     type: 'error',
    //     duration: 5 * 1000
    //   })

    //   // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
    //   if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
    //     // to re-login
    //     MessageBox.confirm('You have been logged out, you can cancel to stay on this page, or log in again', 'Confirm logout', {
    //       confirmButtonText: 'Re-Login',
    //       cancelButtonText: 'Cancel',
    //       type: 'warning'
    //     }).then(() => {
    //       store.dispatch('user/resetToken').then(() => {
    //         location.reload()
    //       })
    //     })
    //   }
    //   return Promise.reject(new Error(res.message || 'Error'))
    // } else {
    //   return res
    // }
  },
  error => {
    if (error.response && error.response.data && error.response.data.code === 10002) {
      Message({
        message: '重新登陆',
        type: 'error',
        duration: 5 * 1000
      })
      //   token失效
      store.dispatch('user/logout')
      router.push('/login')
    }
    console.log('err') // for debug
    console.dir(error)
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
